package com.transaction.simulate.util;

import com.transaction.common.util.CodeUtil;
import com.transaction.common.util.DateUtil;
import com.transaction.simulate.mapper.FundMapper;
import com.transaction.simulate.model.dto.FundYield;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@EnableScheduling
public class TimedTask {


    @Autowired
    private FundMapper fundMapper;

    @Scheduled(cron = "0 0 1 * * ?")
    public void autoInsertFundYield(){
        String transDate = DateUtil.formatDate(new Date(), DateUtil.FORMAT_STR_TIME8);
        insertFundYield(transDate);
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void autoInsertFundNav(){
        String transDate = DateUtil.formatDate(new Date(),DateUtil.FORMAT_STR_TIME8);
        insertFundNav(transDate);
    }


    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void insertFundYield(String transDate) {

        //查询所有的非净值型产品
        List<FundYield> list = fundMapper.selectFundYieldListByFundType("2");

        if(CollectionUtils.isEmpty(list)){
            return;
        }
        list.forEach(v->{
            BigDecimal fundIncome = CodeUtil.generateFundEveryDayIncome();
            BigDecimal yield = CodeUtil.generateFundEveryDayYield();
            v.setFundIncome(fundIncome);
            v.setYield(yield);
            v.setTransDate(transDate);
            fundMapper.deleteFundYieldByChannelFundAndTransDate(v.getChannelCode(),v.getFundCode(),transDate);
        });

        fundMapper.insertEveryDayFundYield(list);

    }

    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void insertFundNav(String transDate) {

        //查询所有的净值型产品
        List<FundYield> list = fundMapper.selectFundYieldListByFundType("1");
        if(CollectionUtils.isEmpty(list)){
            return;
        }

        list.forEach(v->{
            BigDecimal nav = CodeUtil.generateFundEveryDayIncome();
            BigDecimal accumulativeNav = CodeUtil.generateFundEveryDayYield();
            v.setNav(nav);
            v.setAccumulativeNav(accumulativeNav);
            v.setTransDate(transDate);
            fundMapper.deleteFundYieldByChannelFundAndTransDate(v.getChannelCode(),v.getFundCode(),transDate);
        });

        fundMapper.insertEveryDayFundNav(list);

    }

}
